<script setup>
import { ref } from 'vue'
import ChannelSelect from './ChannelSelect.vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {
  artEditService,
  artGetDetailService,
  artPublishService
} from '@/api/article'
import { ElMessage } from 'element-plus'
import { baseURL } from '@/utils/request'
import axios from 'axios'

const imgUrl = ref('')
const editorRef = ref('')
//每次打开重置添加的form
const defaultForm = ref({
  title: '',
  cate_id: '',
  cover_img: '',
  content: '',
  state: ''
})
//提供抽屉的表单数据
const formModel = ref({ ...defaultForm.value })

//新添与修改
const visibleDrawer = ref(false)
const open = async (row) => {
  visibleDrawer.value = true
  if (row.id) {
    const res = await artGetDetailService(row.id)
    formModel.value = { ...res.data.data }
    imgUrl.value = baseURL + res.data.data.cover_img
    const file = await imgUrlToFile(imgUrl.value, formModel.value.cover_img)
    formModel.value.cover_img = file
  } else {
    // 彻底重置：直接赋值 defaultForm.value 的深拷贝
    formModel.value = JSON.parse(JSON.stringify(defaultForm.value))
    imgUrl.value = ''
    // 安全重置富文本（避免 editorRef 未初始化报错）
    editorRef.value?.setHTML('')
  }
}

//处理图片函数
/**
 * 网络图片地址转 File 对象
 * @param {string} imgUrl - 网络图片地址（需跨域支持）
 * @param {string} fileName - 自定义文件名（可选，默认 img.jpg）
 * @returns {Promise<File>} File 对象
 */
const imgUrlToFile = async (imgUrl, fileName = 'img.jpg') => {
  try {
    // 1. 下载图片为 Blob
    const response = await axios.get(imgUrl, {
      responseType: 'blob', // 关键：指定响应类型为 Blob
      headers: {
        Referer: '' // 部分图片需配置 Referer 防盗链，根据实际情况调整
      }
    })
    // 2. 获取图片 MIME 类型（如 image/jpeg、image/png）
    const mimeType = response.headers['content-type'] || 'image/jpeg'
    // 3. Blob 转 File 对象
    const file = new File([response.data], fileName, { type: mimeType })
    return file
  } catch (error) {
    console.error('图片转 File 失败：', error)
    throw error // 抛出错误供上层处理
  }
}

//上传图片
const onUploadFile = (uploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw) //将图片处理成网址访问那种
  formModel.value.cover_img = uploadFile.raw
}

//点击发布与草稿
const emit = defineEmits(['success'])
const onPublish = async (state) => {
  formModel.value.state = state
  const fd = new FormData()
  for (let key in formModel.value) {
    fd.append(key, formModel.value[key])
  }
  if (formModel.value.id) {
    await artEditService(fd)
    ElMessage.success('修改成功')
    visibleDrawer.value = false
    emit('success', 'edit')
  } else {
    await artPublishService(fd)
    ElMessage.success('添加成功')
    visibleDrawer.value = false
    emit('success', 'add') //让列表从新渲染，success函数，add参数
  }
}
defineExpose({
  open
})
</script>
<template>
  <el-drawer
    v-model="visibleDrawer"
    title="添加文章"
    direction="rtl"
    size="50%"
  >
    <el-form label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input placeholder="请输入标题" v-model="formModel.title"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <channel-select
          width="100%"
          v-model="formModel.cate_id"
        ></channel-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <el-upload
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
          v-model="formModel.cover_img"
        >
          <img
            v-if="imgUrl"
            :src="imgUrl"
            class="avatar"
          /><!--这个提交的和显示的不一样-->
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <quill-editor
            ref="editorRef"
            theme="snow"
            v-model="formModel.content"
            contentType="html"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onPublish('已发布')">发布</el-button>
        <el-button type="info" @click="onPublish('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
    <span>Hi there!</span>
  </el-drawer>
</template>

<style lang="scss" scoped>
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
</style>
